package cn.tedu.boot51.controller;

import cn.tedu.boot51.entity.User;
import cn.tedu.boot51.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

@RestController
public class UserController {
    @Autowired
    UserMapper mapper;

    @RequestMapping("reg")
    public int reg(@RequestBody User user) {
        User u = mapper.selectByUsername(user.getUsername());
        if (u != null) {
            return 2; //代表用户名已存在
        }
        mapper.insert(user);
        return 1; //注册成功
    }

    @RequestMapping("login")
    public int login(@RequestBody User user,HttpSession session) {
        User u = mapper.selectByUsername(user.getUsername());
        if(u != null){
            //user表示用户输入的信息,u表示从数据库中查询到的信息
            if(user.getPassword().equals(u.getPassword())) {
                //把当前登录的用户对象保存到会话对象中
                //一个客户端对应一个session对象
                session.setAttribute("user",u);
                return 1; //登录成功
            }
            return 3; //密码错误
        }
        return 2; //用户名不存在
    }

    @RequestMapping("currentUser")
    public User currentUser(HttpSession session) {
        //从会话对象中得到登录成功后的用户对象
        User u = (User)session.getAttribute("user");
        return u;
    }

    @RequestMapping("logout")
    public void logout(HttpSession session) {
        //把登录成功时保存的user对象删除
        session.removeAttribute("user");
    }
}
